package com.cloudwise.thread;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author ：Teacher陈
 * @date ：Created in 2021/1/6 14:32
 * @description：继承方式卖火车票
 * @modified By：
 * @version: 1
 */
public class TicketRunable implements Runnable {


    //票数
    private static  int ticketNum = 5;

    ReentrantLock  lock = new ReentrantLock();
   /* public static  synchronized void saleTicket(){
        if (ticketNum > 0) {
            try {
                TimeUnit.MILLISECONDS.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "卖票" + ticketNum--);
        }
    }*/

    @Override
    public void run() {
        for (int i = 1; i <= 5; i++) {
            //加锁
            lock.lock();
            try {
                if (ticketNum > 0) {
                    try {
                        TimeUnit.MILLISECONDS.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "卖票" + ticketNum--);
                }
            }finally {
                //解锁
                lock.unlock();
            }


        }
    }


    public static void main(String[] args) {
        TicketRunable ticketRunable = new TicketRunable();
        new Thread(ticketRunable, "小昭").start();
        new Thread(ticketRunable, "小敏").start();

    }
}
